﻿using System.Diagnostics;
using System.IO;
using Windows.Storage.Streams;

#if NETFX_CORE
using System;
using System.Threading.Tasks;
#endif

namespace NCache
{
    internal static class Extensions
    {
        public static Stream ToStream(this IRandomAccessStream randomStream)
        {
            if (randomStream == null)
            {
                Debug.WriteLine("read stream is null");
                return null;
            }
            return WindowsRuntimeStreamExtensions.AsStream(randomStream);
        }

        public static byte[] ToByteArray(this Stream stream)
        {
            byte[] buffer = new byte[16 * 1024];
            using (MemoryStream ms = new MemoryStream())
            {
                int read;
                while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    ms.Write(buffer, 0, read);
                }
                return ms.ToArray();
            }
        }

        public static Stream ToStream(this byte[] byteArray)
        {
            return new MemoryStream(byteArray);
        }

#if NETFX_CORE

        public static async Task<IRandomAccessStream> ToRandomStream(this Stream stream)
        {
            var randomAccessStream = new InMemoryRandomAccessStream();
            var outputStream = randomAccessStream.GetOutputStreamAt(0);
            await RandomAccessStream.CopyAsync(stream.AsInputStream(), outputStream);
            return randomAccessStream;
        }
#endif
    }
}
